package org.community.service.detail.userinfo;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import entity.CommonResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.community.service.detail.DetailService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.Map;


//给前端界面显示用户信息
//先找redis再翻数据库
@Data
@Slf4j
@Service
@Transactional(
        isolation = Isolation.REPEATABLE_READ
)
public class UserInfoService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private DetailService detailService;

    //从redis翻找用户信息

    public Map<String,Object> getUserInfoFromRedis(Integer userId){
        StringRedisTemplate redisTemplate = this.getStringRedisTemplate();
        String infoId = redisTemplate.opsForValue().get(Integer.toString(userId));
        if(infoId != null){
            String infoStr = redisTemplate.opsForValue().get(infoId);
            return JSON.parseObject(infoStr);
        }

        return null;

    }



    //从mysql翻找用户信息
    public Map<String,Object> getUserInfoFromMysql(Integer userId){
        CommonResult<Map<String,Object>> res = this.getDetailService().getUserInfoFromDB(userId,1);
        if(res.getCode() == 200){
            return res.getData();
        }
        return null;
    }


    //获取用户信息的总方法
    public Map<String,Object> getUserInfo(Integer userId){
        Map<String,Object> userInfoMap = this.getUserInfoFromRedis(userId);
        if(userInfoMap == null){
            return this.getUserInfoFromMysql(userId);

        }
        return userInfoMap;

    }

    //上传用户信息的接口
    public CommonResult<String> setUserInfo(@RequestBody JSONObject userInfo){
        return this.getDetailService().setUserInfo(userInfo);
    }


    //判断用户存不存在并将存在的用户信息初始化到redis
    public boolean userInfoInitAndCheck(Integer userId){
        int resCode = this.getDetailService().getUserInfoFromDB(userId,1).getCode();
        return resCode != 404;
    }
}
